package com.xkl.springdoc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.xkl.springdoc.common.R;
import com.xkl.springdoc.domain.User;
import com.xkl.springdoc.request.UserDTO;
import com.xkl.springdoc.response.UserVo;
import com.xkl.springdoc.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理
 *
 * @version: 1.0.0-SNAPSHOT
 * @author: 码农小卡拉
 * @createTime: 2025-09-17 11:22
 **/
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private static List<User> userList = new ArrayList<User>();

    @Override
    public R addUser(UserDTO userDTO) {
        log.info("新增用户: {}", userDTO);
        boolean exists = userList.stream().anyMatch(user -> user.getId().equals(userDTO.getId()));
        if (exists) {
            log.error("用户已存在");
            return R.fail("用户已存在");
        }
        User user = new User();
        BeanUtil.copyProperties(userDTO, user);
        user.setCreateTime(DateUtil.date());
        userList.add(user);
        return R.ok();
    }

    @Override
    public R updateUser(UserDTO userDTO) {
        log.info("更新用户: {}", userDTO);
        boolean exists = userList.stream().anyMatch(user -> user.getId().equals(userDTO.getId()));
        if (exists) {
            log.error("用户不存在");
            return R.fail("用户不存在");
        }
        userList.stream().filter(v -> v.getId().equals(userDTO.getId())).findFirst().ifPresent(user -> BeanUtil.copyProperties(userDTO, user, CopyOptions.create().setIgnoreNullValue(true)));
        return R.ok();
    }

    @Override
    public R deleteUser(Long id) {
        return R.ok(userList.removeIf(user -> user.getId().equals(id)));
    }

    @Override
    public R getUser(Long id) {
        User user = userList.stream().filter(v -> v.getId().equals(id)).findFirst().orElse(null);
        if (null == user) {
            log.error("用户不存在");
            return R.fail("用户不存在");
        }
        UserVo vo = new UserVo();
        BeanUtil.copyProperties(user, vo);
        return R.ok(vo);
    }

    @Override
    public R<List<UserVo>> getUsers() {
        List<UserVo> list = userList.stream().map(user -> {
            UserVo vo = new UserVo();
            BeanUtil.copyProperties(user, vo);
            return vo;
        }).toList();
        return R.ok(list);
    }
}
